package com.example.demo;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author 代洪涛
 * @description
 * @create 2018-08-07 下午12:45
 **/

@RunWith(SpringRunner.class)
@SpringBootTest
public class UploadTester {


    @Autowired
    private UploadService uploadService;

    @Test
    public void upload(){

        File file = new File("upload.txt");

        DiskFileItem diskFileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        try (
                InputStream input = new FileInputStream(file);
                OutputStream os = diskFileItem.getOutputStream())
        {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        MultipartFile multipartFile = new CommonsMultipartFile(diskFileItem);

        final String s = uploadService.handleFileUpload(multipartFile);
        System.out.println("dddddd-file-name"+s);

    }
}
